今天不快樂,所以寫個快樂數字。
int squareNumber(int n){
while(n){
int sum = 0;
int digit = n % 10;
sum += digit * digit;
n = n / 10;
}
return sum;
}
class Solution {
public:
int squareNumber(int n){
int sum = 0;
while(n){
int digit = n % 10;
sum += digit * digit;
n = n / 10;
}
return sum;
}
bool isHappy(int n) {
int rabbit = n;
int turtle = n;
do{
turtle = squareNumber(turtle); //run 1 step
rabbit = squareNumber(squareNumber(rabbit)); // run 2 steps
}while(turtle != rabbit); //check
return (turtle == 1);
}
};